# Maintainer: David Macek <david.macek.0@gmail.com>

# TODO: include more stuff from tools/?

_realname=nim
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.11.2
pkgrel=1
pkgdesc='Imperative, multi-paradigm, compiled programming language (mingw-w64)'
arch=('any')
url='http://nim-lang.org/'
license=('MIT')
makedepends=('git')
options=(!emptydirs)
source=("${_realname}::git+https://github.com/Araq/Nim.git#tag=v${pkgver}"
        "${_realname}-build::git+https://github.com/nim-lang/csources"
        "0001-Use-unixy-filenames-even-on-Windows.patch"
        "0002-Recognize-mingw-in-build.sh.patch")
sha256sums=('SKIP'
            'SKIP'
            '3010acbe7769ea214dd51f5889e3a26b44925001905deb04b060beaede2578f4'
            'e53a63a6dc17de6fedebe994c6ae1ac4ea862b10952bf5ffdb690e580a3e69ba')

prepare() {
  cd "${srcdir}"

  rm "${_realname}/build/empty.txt" && rmdir "${_realname}/build"
  cp -R "${_realname}-build" "${_realname}/build"

  cd "${_realname}"
  patch -p1 -i "${srcdir}/0001-Use-unixy-filenames-even-on-Windows.patch"

  pushd build
  patch -p1 -i "${srcdir}/0002-Recognize-mingw-in-build.sh.patch"
  popd
}

build() {
  cd "${srcdir}/${_realname}"

  pushd build
  sh build.sh
  popd

  ./bin/nim c koch
  ./koch boot -d:release -d:useGnuReadline

  export PATH="${srcdir}/${_realname}/bin:$PATH"

  pushd lib
  nim c --app:lib -d:createNimRtl -d:release nimrtl.nim
  popd

  pushd tools
  nim c -d:release nimgrep.nim
  popd
}

package() {
  cd "${srcdir}/${_realname}"

  export PATH="${srcdir}/${_realname}/bin:$PATH"

  ./koch install "${pkgdir}"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/bin"
  # mv "${pkgdir}/nim/bin"/* "${pkgdir}${MINGW_PREFIX}/bin/"
  cp "bin/nim.exe" "${pkgdir}${MINGW_PREFIX}/bin/"
  cp "tools/nimgrep.exe" "${pkgdir}${MINGW_PREFIX}/bin/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/lib/nim"
  mv "${pkgdir}/nim/lib"/* "${pkgdir}${MINGW_PREFIX}/lib/nim/"
  cp -a "lib/packages" "${pkgdir}${MINGW_PREFIX}/lib/nim/"
  cp "lib/libnimrtl.dll" "${pkgdir}${MINGW_PREFIX}/lib/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/etc"
  mv "${pkgdir}/nim/config"/* "${pkgdir}${MINGW_PREFIX}/etc/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/share/nim/doc"
  cp -r "examples" "web" "${pkgdir}${MINGW_PREFIX}/share/nim/doc/"
  cp -r "doc"/* "${pkgdir}${MINGW_PREFIX}/share/nim/doc/"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
  cp "copying.txt" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  # clean up after koch install
  rm -r "${pkgdir}/nim"
}
